package com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.service.business.user.convert;

import cn.hutool.json.JSONObject;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.api.model.business.staff.*;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.api.model.business.staff.extend.BIPUser;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.api.model.core.constant.CommonConstant;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.SdwcoatencentConnection;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.service.core.ParamConvertService;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.utils.LogUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class UserParamConvertService implements ParamConvertService<BaseUser, BIPUser> {
    @Override
    public List<BaseUser> convertForBatchSave(List<BIPUser> list, SdwcoatencentConnection connection) {
        List<BaseUser> baseUserList = new ArrayList();
        Iterator var4 = list.iterator();

        while(true) {
            BIPUser user;
            Boolean syncFlag;
            do {
                if (!var4.hasNext()) {
                    return baseUserList;
                }

                user = (BIPUser)var4.next();
                syncFlag = user.getSyncFlag();
            } while(!syncFlag);

            this.dealExtattr(user);
            this.dealExtProfileAttr(user);
            List<StaffJob> mainJobList = (List)user.getMainJobList().stream().map((job) -> {
                job.setMainJob(true);
                return job;
            }).collect(Collectors.toList());
            List<StaffJob> partJobList = user.getPartJobList();
            if (CollectionUtils.isNotEmpty(mainJobList) || CollectionUtils.isNotEmpty(partJobList)) {
                Boolean needMergePartJob = user.getNeedMergePartJob();
                if (CollectionUtils.isNotEmpty(partJobList)) {
                    if (needMergePartJob) {
                        try {
                            partJobList = mergeJob(partJobList);
                        } catch (ParseException var20) {
                            LogUtils.printStacktrace(var20);
                        }
                    }

                    mainJobList.addAll(partJobList);
                }

                List<StaffJob> latestWorkList = (List)mainJobList.stream().filter((staffJob) -> {
                    return staffJob.getSyncFlag();
                }).filter((staffJob) -> {
                    try {
                        return this.judgeEnddate(staffJob.getStartdate(), staffJob.getEnddate());
                    } catch (ParseException var3) {
                        LogUtils.printStacktrace(var3);
                        return false;
                    }
                }).collect(Collectors.toList());
                if (latestWorkList.size() <= 0) {
                    LogUtils.apiRequestInfo("latestWorkList", "Abnormal employee employment information with no eligible employment records");
                } else {
                    List<Long> departmentList = new ArrayList();
                    List<Integer> orderList = new ArrayList();
                    Iterator var14 = latestWorkList.iterator();

                    while(var14.hasNext()) {
                        StaffJob staffJobTemp = (StaffJob)var14.next();
                        String deptId = staffJobTemp.getDeptId();
                        Boolean mainJob = staffJobTemp.getMainJob();
                        if (mainJob) {
                            if (StringUtils.isNotBlank(deptId)) {
                                user.setMain_department(deptId);
                            }

                            String jobname = staffJobTemp.getJobname();
                            user.setPosition(jobname);
                            if (StringUtils.isNotBlank(staffJobTemp.getDirector())) {
                                List<String> directLeaderList = new ArrayList();
                                directLeaderList.add(staffJobTemp.getDirector());
                                user.setDirect_leader(directLeaderList);
                            }
                        }

                        if (StringUtils.isNotBlank(deptId)) {
                            departmentList.add(Long.valueOf(deptId));
                            orderList.add(CommonConstant.USER_MAX_LEVEL - user.getOrderNum());
                        }
                    }

                    user.setDepartment(departmentList);
                    user.setOrder(orderList);
                }
            }

            baseUserList.add(user);
        }
    }


    private List<StaffJob> mergeJob(List<StaffJob> staffJobList) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer[] endTrnsEventArr = new Integer[]{7, 10, 13, 16, 19};
        List<StaffJob> mergeList = new ArrayList();
        sortJobListByJobIdAndRecordNum(staffJobList);
        StaffJob tempFirstStaffJob = new StaffJob();
        StaffJob tempLastStaffJob = new StaffJob();
        String tempStaffJobId = null;
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(1);
        int month = calendar.get(2) + 1;
        int day = calendar.get(5);
        Date toDay = sdf.parse(year + "-" + month + "-" + day + " 00:00:00");
        long toDayTime = toDay.getTime();

        for(int i = 0; i < staffJobList.size(); ++i) {
            StaffJob job = (StaffJob)staffJobList.get(i);
            if (StringUtils.isBlank(tempStaffJobId)) {
                tempStaffJobId = job.getStaffjobId();
                tempFirstStaffJob = job;
                tempLastStaffJob = job;
                if (i == staffJobList.size() - 1) {
                    mergeList.add(job);
                }
            } else {
                List<Integer> endTrnsEventList = new ArrayList(Arrays.asList(endTrnsEventArr));
                String startdate;
                Date parseStartDate;
                Calendar instance;
                Date time;
                String enddate;
                Date parseEnddate;
                long endTime;
                long startTime;
                if (tempStaffJobId.equals(job.getStaffjobId())) {
                    tempLastStaffJob = job;
                    if (i == staffJobList.size() - 1) {
                        if (endTrnsEventList.contains(job.getTrnsEvent())) {
                            startdate = job.getStartdate();
                            parseStartDate = sdf.parse(startdate);
                            instance = Calendar.getInstance();
                            instance.setTime(parseStartDate);
                            instance.add(5, -1);
                            time = instance.getTime();
                            enddate = sdf.format(time);
                            tempFirstStaffJob.setEnddate(enddate);
                        } else {
                            tempFirstStaffJob.setEnddate((String)null);
                        }

                        startdate = job.getStartdate();
                        parseStartDate = sdf.parse(startdate);
                        startTime = parseStartDate.getTime();
                        enddate = job.getEnddate();
                        if (StringUtils.isBlank(enddate)) {
                            if (toDayTime >= startTime) {
                                tempFirstStaffJob.setDeptId(job.getDeptId());
                                tempFirstStaffJob.setJobname(job.getJobname());
                                tempFirstStaffJob.setSyncFlag(job.getSyncFlag());
                            }
                        } else {
                            parseEnddate = sdf.parse(enddate);
                            endTime = parseEnddate.getTime();
                            if (toDayTime >= startTime && toDayTime <= endTime) {
                                tempFirstStaffJob.setDeptId(job.getDeptId());
                                tempFirstStaffJob.setJobname(job.getJobname());
                                tempFirstStaffJob.setSyncFlag(job.getSyncFlag());
                            }
                        }

                        mergeList.add(tempFirstStaffJob);
                    } else {
                        startdate = job.getStartdate();
                        parseStartDate = sdf.parse(startdate);
                        startTime = parseStartDate.getTime();
                        enddate = job.getEnddate();
                        if (StringUtils.isBlank(enddate)) {
                            if (toDayTime >= startTime) {
                                tempFirstStaffJob.setDeptId(job.getDeptId());
                                tempFirstStaffJob.setJobname(job.getJobname());
                                tempFirstStaffJob.setSyncFlag(job.getSyncFlag());
                            }
                        } else {
                            parseEnddate = sdf.parse(enddate);
                            endTime = parseEnddate.getTime();
                            if (toDayTime >= startTime && toDayTime <= endTime) {
                                tempFirstStaffJob.setDeptId(job.getDeptId());
                                tempFirstStaffJob.setJobname(job.getJobname());
                                tempFirstStaffJob.setSyncFlag(job.getSyncFlag());
                            }
                        }
                    }
                } else {
                    tempStaffJobId = job.getStaffjobId();
                    if (endTrnsEventList.contains(tempLastStaffJob.getTrnsEvent())) {
                        startdate = tempLastStaffJob.getStartdate();
                        parseStartDate = sdf.parse(startdate);
                        instance = Calendar.getInstance();
                        instance.setTime(parseStartDate);
                        instance.add(5, -1);
                        time = instance.getTime();
                        enddate = sdf.format(time);
                        tempFirstStaffJob.setEnddate(enddate);
                    } else {
                        tempFirstStaffJob.setEnddate((String)null);
                    }

                    startdate = tempLastStaffJob.getStartdate();
                    parseStartDate = sdf.parse(startdate);
                    startTime = parseStartDate.getTime();
                    enddate = tempLastStaffJob.getEnddate();
                    if (StringUtils.isBlank(enddate)) {
                        if (toDayTime >= startTime) {
                            tempFirstStaffJob.setDeptId(tempLastStaffJob.getDeptId());
                            tempFirstStaffJob.setJobname(tempLastStaffJob.getJobname());
                            tempFirstStaffJob.setSyncFlag(tempLastStaffJob.getSyncFlag());
                        }
                    } else {
                        parseEnddate = sdf.parse(enddate);
                        endTime = parseEnddate.getTime();
                        if (toDayTime >= startTime && toDayTime <= endTime) {
                            tempFirstStaffJob.setDeptId(tempLastStaffJob.getDeptId());
                            tempFirstStaffJob.setJobname(tempLastStaffJob.getJobname());
                            tempFirstStaffJob.setSyncFlag(tempLastStaffJob.getSyncFlag());
                        }
                    }

                    mergeList.add(tempFirstStaffJob);
                    tempFirstStaffJob = job;
                    tempLastStaffJob = job;
                    if (i == staffJobList.size() - 1) {
                        mergeList.add(job);
                    }
                }
            }
        }

        return mergeList;
    }
    public static void sortJobListByJobIdAndRecordNum(List<StaffJob> staffJobList) {
        Collections.sort(staffJobList, new Comparator<StaffJob>() {
            public int compare(StaffJob j1, StaffJob j2) {
                return !j1.getStaffjobId().equals(j2.getStaffjobId()) ? j1.getStaffjobId().compareTo(j2.getStaffjobId()) : Integer.compare(j2.getRecordNum(), j1.getRecordNum());
            }
        });
    }

    @Override
    public List<BaseUser> convertForBatchDelete(List<BIPUser> list, SdwcoatencentConnection connection) {
        return (List)list.stream().collect(Collectors.toList());
    }

    @Override
    public BaseUser convertForSave(BIPUser objet, SdwcoatencentConnection connection) {
        return null;
    }

    @Override
    public BaseUser convertForDelete(BIPUser objet, SdwcoatencentConnection connection) {
        return null;
    }

    private boolean judgeEnddate(String startdate, String enddate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        boolean flag = false;
        Date parseStartDate = sdf.parse(startdate);
        long currentTimeMillis = System.currentTimeMillis();
        if (parseStartDate.getTime() <= currentTimeMillis) {
            if (enddate != null) {
                Date parseEndDate = sdf.parse(enddate);
                if (parseEndDate.getTime() >= currentTimeMillis) {
                    flag = true;
                } else {
                    flag = false;
                }
            } else {
                flag = true;
            }
        }

        return flag;
    }
    private BaseUser dealExtProfileAttr(BIPUser user) {
        ExtattrObj externalProfileAttrObj = user.getExternalProfileAttrObj();
        if (externalProfileAttrObj != null) {
            ExternalProfile externalProfile = new ExternalProfile();
            List<Map<String, Object>> attrs = new ArrayList();
            this.commonDealAttrMap(externalProfileAttrObj, attrs);
            externalProfile.setExternal_attr(attrs);
            user.setExternal_profile(externalProfile);
        }

        return user;
    }
    private List<Map<String, Object>> commonDealAttrMap(ExtattrObj externalProfileAttrObj, List<Map<String, Object>> attrs) {
        Map<String, Object> textMap = externalProfileAttrObj.getTextMap();
        if (textMap != null) {
            this.dealExtattrMap(textMap, 0, "text", attrs);
        }

        Map<String, Object> webMap = externalProfileAttrObj.getWebMap();
        if (webMap != null) {
            this.dealExtattrMap(webMap, 1, "web", attrs);
        }

        Map<String, Object> miniprogramMap = externalProfileAttrObj.getMiniprogramMap();
        if (miniprogramMap != null) {
            this.dealExtattrMap(miniprogramMap, 2, "miniprogram", attrs);
        }

        return attrs;
    }
    private BaseUser dealExtattr(BIPUser user) {
        ExtattrObj extattrObj = user.getExtattrObj();
        if (extattrObj != null) {
            UserExtList extattr = new UserExtList();
            List<Map<String, Object>> attrs = new ArrayList();
            this.commonDealAttrMap(extattrObj, attrs);
            extattr.setAttrs(attrs);
            user.setExtattr(extattr);
        }

        return user;
    }

    private List<Map<String, Object>> dealExtattrMap(Map<String, Object> attrMap, int type, String typeName, List<Map<String, Object>> attrs) {
        Iterator var6 = attrMap.entrySet().iterator();

        while(var6.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry)var6.next();
            JSONObject attrObj = new JSONObject();
            String key = (String)entry.getKey();
            Object value = entry.getValue();
            attrObj.set("type", type);
            attrObj.set("name", key);
            attrObj.set(typeName, value);
            attrs.add(attrObj);
        }

        return attrs;
    }
}
